/**
 *
 */
package org.gbif.crawler.console.action;

import org.gbif.crawler.console.model.SearchResult;
import org.gbif.crawler.service.api.model.CrawlableResource;
import org.gbif.crawler.service.api.service.CrawlableResourceService;

import java.util.LinkedList;
import java.util.List;

import com.google.inject.Inject;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author tim
 */
public class SearchAction extends ActionSupport {
  private static final Logger LOG = LoggerFactory.getLogger(SearchAction.class);
  private static final long serialVersionUID = 284183831345420215L;
  private String q;
  private List<SearchResult> results;
  public static final int MAX_TITLE_LENGTH = 100;

  @Inject
  private CrawlableResourceService crawlableResourceService;

  public String getQ() {
    return q;
  }

  public List<SearchResult> getResults() {
    return results;
  }

  public String index() {
    results = new LinkedList<SearchResult>();

    if (StringUtils.isNotBlank(q)) {
      List<CrawlableResource> resources = crawlableResourceService.list(q.split(" "));
      for (CrawlableResource r : resources) {
        results.add(new SearchResult(
            r.getKey(),
            truncate(r.getName(), MAX_TITLE_LENGTH),
            truncate(r.getOrganizationName(), MAX_TITLE_LENGTH),
            "unknown",
            r.getUrl(),
            r.getMaxCrawled(),
            "" + r.getLastSeenOnline()
            ));
      }
    }
    return ActionSupport.SUCCESS;
  }

  public void setQ(String q) {
    this.q = q;
  }

  /**
   * Truncates if needed
   */
  private String truncate(String s, int length) {
    if (s!=null && s.length()>length) {
      return s.substring(0, length) + "...";
    }
    return s;
  }
}
